package com.pinganfu.mock.control;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;



import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;



import org.apache.commons.codec.binary.Hex;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pinganfu.mock.model.SynchronousMouldEntity;
import com.pinganfu.mock.service.IMethodService;
import com.pinganfu.mock.service.ISynchronousMouldService;
import com.pinganfu.mock.service.ISynchronousResultService;



@Controller
@RequestMapping(value = "/Synchronous", produces = { "application/json;charset=UTF-8"})
public class SynchronousControl {
	
	@Resource
	private ISynchronousMouldService synchronousMouldService;
	
	@Resource
	private ISynchronousResultService iSynchronousResultService;
	
	@Resource
	private IMethodService iMethodService;
	
	
	/*******************************************分割线-----http**************************************************/
	
	/**
	 * 按条件查询数据
	 * @param id
	 * @param serviceName
	 * @param response 
	 * @return
	 */
	@RequestMapping(value="/getSynchronousHttpMouldList",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String getSynchronousHttpMouldList(@RequestParam(required = false) Integer  id,@RequestParam(required = false) String  serviceName){
		//response.setContentType("application/json;charset=UTF-8");//防止数据传递乱码
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != id)
			resultMap.put("id", id);
		if (null != serviceName)
		   	resultMap.put("serviceName", serviceName);
		
		//SynchronousMouldServiceImpl synchronousMouldService = new SynchronousMouldServiceImpl();
		List<SynchronousMouldEntity> entities  =   synchronousMouldService.getSynchronousHttpMouldList(resultMap);
		
		//String json2 = JSON.toJSONString(entities);
		//System.out.println(json);
		//System.out.println(json2);
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("synMouldList", entities);
   		return json.messageToJsonString();
	}
	
	
	@RequestMapping(value="/insertSynchronousHttpMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String insertSynchronousHttpMould(
			@RequestParam String serviceName,
			@RequestParam String url,
			@RequestParam String mould,
			@RequestParam String format
			){
		SynchronousMouldEntity entity = new SynchronousMouldEntity();
		entity.setServiceName(serviceName);
		entity.setUrl(url);
		entity.setMould(mould);
		entity.setFormat(format);
		entity.setCreateTime(new Date());
		
		Integer id = synchronousMouldService.insertSynchronousHttpMould(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("insertSynMould", id);
   		return json.messageToJsonString();
	}
	
	
	
	@RequestMapping(value="/updateSynchronousHttpMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String updateSynchronousHttpMould(
			@RequestParam Integer id,
			@RequestParam String serviceName,
			@RequestParam String url,
			@RequestParam String mould,
			@RequestParam String format
			){
		SynchronousMouldEntity entity = new SynchronousMouldEntity();
		if (null != id)
			entity.setId(id);
		if (null != serviceName)
			entity.setServiceName(serviceName);
		if (null != url)
			entity.setUrl(url);
		if (null != mould)
			entity.setMould(mould);
		if (null != format)
			entity.setFormat(format);
		
		synchronousMouldService.updateSynchronousHttpMould(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("updateSynMould", id);
   		return json.messageToJsonString();
	}
	
	
	@RequestMapping(value="/delSynchronousHttpMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String delSynchronousHttpMould(
			@RequestParam Integer id
			){
		SynchronousMouldEntity entity = new SynchronousMouldEntity();
		entity.setId(id);
		
		synchronousMouldService.delSynchronousHttpMould(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("delSynMould", entity.getId());
   		return json.messageToJsonString();
	}
	
	
	/*******************************************分割线-----https**************************************************/
	
	/**
	 * 按条件查询数据
	 * @param id
	 * @param serviceName
	 * @param response 
	 * @return
	 */
	@RequestMapping(value="/getSynchronousHttpsMouldList",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String getSynchronousHttpsMouldList(@RequestParam(required = false) Integer  id,@RequestParam(required = false) String  serviceName){
		//response.setContentType("application/json;charset=UTF-8");//防止数据传递乱码
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != id)
			resultMap.put("id", id);
		if (null != serviceName)
		   	resultMap.put("serviceName", serviceName);
		
		//SynchronousMouldServiceImpl synchronousMouldService = new SynchronousMouldServiceImpl();
		List<SynchronousMouldEntity> entities  =   synchronousMouldService.getSynchronousHttpsMouldList(resultMap);
		
		//String json2 = JSON.toJSONString(entities);
		//System.out.println(json);
		//System.out.println(json2);
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("synMouldList", entities);
   		return json.messageToJsonString();
	}
	
	
	@RequestMapping(value="/insertSynchronousHttpsMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String insertSynchronousHttpsMould(
			@RequestParam String serviceName,
			@RequestParam String encrypt,
			@RequestParam String url,
			@RequestParam String mould
			){
		SynchronousMouldEntity entity = new SynchronousMouldEntity();
		entity.setServiceName(serviceName);
		entity.setEncrypt(encrypt);
		entity.setUrl(url);
		entity.setMould(mould);
		entity.setCreateTime(new Date());
		
		Integer id = synchronousMouldService.insertSynchronousHttpsMould(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("insertSynMould", id);
   		return json.messageToJsonString();
	}
	
	
	
	@RequestMapping(value="/updateSynchronousHttpsMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String updateSynchronousHttpsMould(
			@RequestParam Integer id,
			@RequestParam String serviceName,
			@RequestParam String encrypt,
			@RequestParam String url,
			@RequestParam String mould
			){
		SynchronousMouldEntity entity = new SynchronousMouldEntity();
		if (null != id)
			entity.setId(id);
		if (null != serviceName)
			entity.setServiceName(serviceName);
		if(null != encrypt)
			entity.setEncrypt(encrypt);
		if (null != url)
			entity.setUrl(url);
		if (null != mould)
			entity.setMould(mould);
		
		synchronousMouldService.updateSynchronousHttpsMould(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("updateSynMould", id);
   		return json.messageToJsonString();
	}
	
	
	@RequestMapping(value="/delSynchronousHttpsMould",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String delSynchronousHttpsMould(
			@RequestParam Integer id
			){
		SynchronousMouldEntity entity = new SynchronousMouldEntity();
		entity.setId(id);
		
		synchronousMouldService.delSynchronousHttpsMould(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("delSynMould", entity.getId());
   		return json.messageToJsonString();
	}
	
	
	
	/*@RequestMapping(value="/getSynchronousResultByUrl",method={ RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8")
	public @ResponseBody String getSynchronousResultByUrl(@RequestParam(required = false) String  url){
		String json="无数据";
		
		if(null != url){
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("url", url);
			
			String result=iSynchronousResultService.getSynchronousResultByUrl(resultMap);
			
			String[] trends = {"test","test1"};
			for (int i = 0; i < trends.length; i++) {
				System.out.println(trends[i]);
			}
 			json = result;
			
		}
		return json;
	}
	
	
	@RequestMapping(value="/insertSynchronousResult",method = { RequestMethod.GET, RequestMethod.POST })
	public @ResponseBody String insertSynchronousResult(
			@RequestParam String serviceName,
			@RequestParam String url,
			@RequestParam String mouldContent
			){
		SynchronousResultEntity entity = new SynchronousResultEntity();
		entity.setServiceName(serviceName);
		entity.setUrl(url);
		entity.setMouldContent(mouldContent);
		entity.setCreateTime(new Date());
		
		Integer id = iSynchronousResultService.insertSynchronousResult(entity);
		
		AbsJsonObject json = new AbsJsonObject(AbsJsonObject.SUCCESS_OK);
   		json.addMessage("insertSynResult", id);
   		return json.messageToJsonString();
	}
*/

	/*@RequestMapping(value="/test",method={ RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8")
	public @ResponseBody String test(){
		//String json="{\"businessParameters\":{\"retcode\":\"0009\",\"retmsg\":\"交易不存在\"},\"protocolParameters\":{\"input_charset\":\"UTF-8\",\"service_version\":\"1.0\",\"sign\":\"F121EBBDB369C794A7391CDC85B608103C845F41\",\"sign_key_index\":1,\"sign_type\":\"SHA-1\"}}";
		String contentInfo = "{\"businessParameters\":{\"attach\":\"\",\"fee_type\":\"\",\"fund_trade_no\":\"009201510230000000297\",\"partner\":\"270\",\"retcode\":\"0000\",\"retmsg\":\"\",\"sign_key_index\":\"1\",\"sp_user\":\"00999000008334820\",\"time_end\":\"20151023140906\",\"total_fee\":\"9853.05\",\"total_fund_units\":\"9903.05\",\"transaction_id\":\"00500010201510230033330000463593\"},\"protocolParameters\":{\"channel_id\":\"PAF\",\"input_charset\":\"GBK\",\"service_version\":\"1.0\",\"sign\":\"47FF4944F159F95DB9F47FF5B4412F89B658A1C9\",\"sign_type\":\"SHA-1\"}}";
		//SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		//String request_time = df.format(new Date());
		//for (int i = 0; i < contentInfo.length(); i++) {
			
		//}
		//	String[] trends = {"attach","fee_type"};
		//	for (int i = 0; i < trends.length; i++) {
		//		System.out.println(trends[i]);
		//	}
		String json = JSON.toJSONString(contentInfo);
		
		List<String> entity = iTrendsService.getTrendsList();
		final int size =  entity.size();
		String[] arr = (String[])entity.toArray(new String[size]);
		for (int i = 0; i < arr.length; i++) {
			if ("date".equals(arr[i])) {
				String d = iTrendsService.getTrendsValue(arr[i]);
				String c = trendsData.trendString(d);
				System.out.println(c);
			}
			
		}
		
		return json;
	}*/
	
	@RequestMapping(value="/httpTEST/{url}",method={ RequestMethod.GET,RequestMethod.POST },produces = "application/json; charset=utf-8")
	 public @ResponseBody String ajax(@PathVariable String url,HttpServletRequest request) {
		
		String str = "";
		StringBuffer sb = new StringBuffer() ; 
		InputStream is;
		try {
			is = request.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);   
		BufferedReader br = new BufferedReader(isr); 
		String s = "" ; 
		while((s=br.readLine())!=null){ 
		sb.append(s) ; 
		} 
		str =sb.toString(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		if (str.equals("")) {
			str="123";
		}
		return str;
    }
	
	
	
	@RequestMapping(value="/http/{url}",method={ RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8")
	public @ResponseBody String test2(@PathVariable String url,HttpServletRequest request){
		
		String json = "未知异常"; 
		
		System.out.println(url);
		
		
		String parameter = "";
		StringBuffer sb = new StringBuffer() ; 
		InputStream is;
		try {
			is = request.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);   
			BufferedReader br = new BufferedReader(isr); 
			String s = "" ; 
			while((s=br.readLine())!=null){ 
				sb.append(s) ; 
			} 
			parameter =sb.toString(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		System.out.println(parameter);
		if(url.equals("nanfang") && !parameter.equals("")){
			parameter = parameter.substring(parameter.indexOf("<body>")+6,parameter.indexOf("</body>"));
			try {
				parameter = URLDecoder.decode(parameter,"GBK");
				parameter = "<body>"+parameter+"</body>";
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(url.equals("dahuajijin") && !parameter.equals("")){
			parameter = "{\""+parameter+"\"}";
			try {
				parameter = URLDecoder.decode(parameter,"GBK");
				parameter = parameter.replace("&", "\",\"");
				parameter = parameter.replace("=", "\"=\"");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(parameter.indexOf("<")>=0){
			XMLSerializer xmlSerializer = new XMLSerializer();
			System.out.println(1);
			JSON j = xmlSerializer.read(parameter); 
			
			parameter = j.toString();
			
			System.out.println(parameter);
		}
		
		
		//url = "http://localhost:8080/MockPlatform/Synchronous/"+url;
		url = "http://10.59.33.49:8080/MockPlatform/Synchronous/http/"+url;
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != url)
			resultMap.put("url", url);
		
		//拿到模板
		String data = synchronousMouldService.getSynchronousHttpMouldByUrl(resultMap);
		
		String format = synchronousMouldService.getSynchronousHttpMouldFormat(resultMap);
		if(data.indexOf("<")>=0){
			if (data.indexOf("\n")>=0) {
				
				String test1 = data.replace("\n","");
				data = test1;
			}
			XMLSerializer xmlSerializer = new XMLSerializer();
			JSON j = xmlSerializer.read(data); 
			data = j.toString();
			
		}else{
			if (data.indexOf("\n")>=0) {
				String test1 = data.replace("\n","");
				data = test1;
			}
		}
		System.out.println("============="+data);
		
		String SOUTH_KEY_DOCKER = "PAF567890ABCDEFG";
		if (!parameter.equals("")) {
			trendsData trData = new trendsData();
			if (format.equals("xml")) {
				json = trData.json(parameter, data);
				JSONObject jsonObj=new JSONObject(json);
				 //json=
				if(url.equals("http://10.59.33.49:8080/MockPlatform/Synchronous/http/nanfang")){
					try {
						json =URLEncoder.encode(XML.toString(jsonObj),"GBK");
						String sign=sign(SOUTH_KEY_DOCKER+json+SOUTH_KEY_DOCKER,"GBK");
						json = "<?xml version=\"1.0\" encoding=\"GBK\"?><Message><body>"+json
								+"</body><sign>"+sign+"</sign></Message>";
					} catch (UnsupportedEncodingException e) {
						System.out.println("南方基金户报文加密出错");
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else{
					json = "<?xml version=\"1.0\" encoding=\"GBK\"?><root>"+XML.toString(jsonObj)+"</root>";
				}
				
			}else{
				json = trData.json(parameter, data);
			}
			
			  
		}else {
			json = data;
		}
		
	    
	    return json;
	}
	
	
	
	@RequestMapping(value="/https/{url}",method={ RequestMethod.GET, RequestMethod.POST },produces = "application/json; charset=utf-8")
	public @ResponseBody String test3(@PathVariable String url,HttpServletRequest request) throws Exception{
		
		String json="";
		System.out.println(url);
		
		
		String parameter = "";
		StringBuffer sb = new StringBuffer() ; 
		InputStream is;
		try {
			is = request.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);   
			BufferedReader br = new BufferedReader(isr); 
			String s = "" ; 
			while((s=br.readLine())!=null){ 
				sb.append(s) ; 
			} 
			parameter =sb.toString(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		
		//url = "http://localhost:8080/MockPlatform/Synchronous/"+url;
		url = "http://10.59.33.49:8080/MockPlatform/Synchronous/https/"+url;
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null != url)
			resultMap.put("url", url);
		
		//拿到加密方法
		String encrypt = synchronousMouldService.getSynchronousHttpsMouldEncrypt(resultMap);
		
		//拿到模板
		String data = synchronousMouldService.getSynchronousHttpsMouldByUrl(resultMap);
		
		
		if (!parameter.equals("")) {
			trendsData trData = new trendsData();
			json = trData.json_encrypt(encrypt,parameter, data);
			
		}else {
			json = data;
		}
		
		//拿到动态方法集合
		//String[] arr = iMethodService.getMethodName();
		
		/*//对json数据进行解析
		Map map=new HashMap();  
        JsonConfig jc=new JsonConfig();  
        jc.setClassMap(map);  
        jc.setRootClass(Map.class);  
        jc.setArrayMode(JsonConfig.MODE_LIST);  
        JSONObject jobj=JSONObject.fromObject(data,jc); 
        
		//trendsData trend = new trendsData();
	        //递归遍历  
	    //String heheString =trend.data(arr,data);
	        String json =decodeJSONObject(arr,jobj);*/
	       return json;
	}
	
	
	
	
	/*//对json数据进行解析修改
	public String decodeJSONObject(String[] arr,JSONObject json){ 
		Iterator<String> keys=json.keys(); 
		JSONObject jo=null;
		JSONArray ja = null;
		Object o; 
		String key; 
		while(keys.hasNext()){ 
			key=keys.next(); 
			o=json.get(key); 
			if(o instanceof JSONObject){ 
				jo=(JSONObject)o; 
				if(jo.keySet().size()>0){ 
					decodeJSONObject(arr,jo);
				}else{ 
					System.out.println("key "+key); 
				} 
			}else if(o instanceof JSONArray){
				ja = (JSONArray)o;
				for(int i=0;i<ja.size();i++){
					decodeJSONObject(arr,ja.getJSONObject(i));
				}
			}else{
				for (int i = 0; i < arr.length; i++) {
					String cString = "${"+arr[i]+"}";
					System.out.println(o);
					if(cString.equals(o))
					{
						trendsData trend = new trendsData();
						String tString = trend.trendString(arr[i]);
						System.out.println(tString);
						json.put(key, tString);
					}
				}
				//System.out.println("value"+"--"+key+"--"+o);
			}
		} 
		String hehe = String.valueOf(json);
		return hehe;
	}*/
	
	
	
	public static String sign(String str, String charset) {
	      MessageDigest md = null;
	      String result = null;
	      try {
	        md = MessageDigest.getInstance("MD5");
	        md.reset();
	        byte[] bt = null;
	        bt = str.getBytes(charset);
	        md.update(bt);
	        byte[] digest = md.digest();
	        result = new String(Hex.encodeHex(digest));
	      } catch (Exception e) {
	    	  System.out.println("获取MD5实例失败");
	        //log.error("获取MD5实例失败", e);
	      }
	      System.out.println(result);
	      return result;
	   }
}
